/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.edu.javeriana.presentacion;

import co.edu.javeriana.comunicacion.Constantes;
import co.edu.javeriana.negocio.Estacion;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.image.BufferedImage;

import java.util.ArrayList;
import javax.swing.ImageIcon;
import org.jfree.chart.ChartFactory;

import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.ThermometerPlot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.general.DefaultValueDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 *
 * @author Juan Pablo Granados
 */
public class MainWindow extends javax.swing.JFrame {

    Estacion miEstacion;
    ThermometerPlot plot;
    
    /**
     * Creates new form MainWondow
     */
    public MainWindow() {
        initComponents();
        Constantes.cargaPropiedades();
        this.setTitle(Constantes.ESTACION);
        
        plot = new ThermometerPlot(new DefaultValueDataset(new Double(0.0)));
        plot.setSubrangeInfo(ThermometerPlot.NORMAL, 0.0, 40.0, 0.0, 100.0);
        plot.setSubrangeInfo(ThermometerPlot.WARNING, 40.0, 50.0, 0.0, 100.0);
        plot.setSubrangeInfo(ThermometerPlot.CRITICAL, 50.0, 100.0, 0.0, 100.0);
        plot.setThermometerStroke(new BasicStroke(2.0f));
        plot.setThermometerPaint(Color.blue);
        
        miEstacion = new Estacion(this);
        sliderFrecuencia.setValue((int) miEstacion.getFrecuencia());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanelLineal = new javax.swing.JPanel();
        jLabelLineal = new javax.swing.JLabel();
        comboEstaciones = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        sliderFrecuencia = new javax.swing.JSlider();
        jLabel2 = new javax.swing.JLabel();
        jPanelTermometro = new javax.swing.JPanel();
        jLabelTermometro = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanelLineal.setPreferredSize(new java.awt.Dimension(500, 300));

        javax.swing.GroupLayout jPanelLinealLayout = new javax.swing.GroupLayout(jPanelLineal);
        jPanelLineal.setLayout(jPanelLinealLayout);
        jPanelLinealLayout.setHorizontalGroup(
            jPanelLinealLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 500, Short.MAX_VALUE)
        );
        jPanelLinealLayout.setVerticalGroup(
            jPanelLinealLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        comboEstaciones.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboEstacionesActionPerformed(evt);
            }
        });

        jLabel1.setText("Estación");

        sliderFrecuencia.setMajorTickSpacing(2);
        sliderFrecuencia.setMaximum(20);
        sliderFrecuencia.setMinimum(1);
        sliderFrecuencia.setMinorTickSpacing(1);
        sliderFrecuencia.setPaintLabels(true);
        sliderFrecuencia.setPaintTicks(true);
        sliderFrecuencia.setValue(10);
        sliderFrecuencia.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                sliderFrecuenciaMouseReleased(evt);
            }
        });

        jLabel2.setText("Frecuencia (Segundos)");

        jPanelTermometro.setPreferredSize(new java.awt.Dimension(180, 300));

        jLabelTermometro.setText("Esperando lectura del sensor...");

        javax.swing.GroupLayout jPanelTermometroLayout = new javax.swing.GroupLayout(jPanelTermometro);
        jPanelTermometro.setLayout(jPanelTermometroLayout);
        jPanelTermometroLayout.setHorizontalGroup(
            jPanelTermometroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelTermometroLayout.createSequentialGroup()
                .addComponent(jLabelTermometro)
                .addGap(0, 29, Short.MAX_VALUE))
        );
        jPanelTermometroLayout.setVerticalGroup(
            jPanelTermometroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelTermometroLayout.createSequentialGroup()
                .addComponent(jLabelTermometro)
                .addGap(0, 286, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(35, 35, 35)
                        .addComponent(jPanelTermometro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(39, 39, 39)
                        .addComponent(jLabelLineal)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanelLineal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(comboEstaciones, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addGap(9, 9, 9)
                        .addComponent(sliderFrecuencia, javax.swing.GroupLayout.PREFERRED_SIZE, 379, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(24, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(comboEstaciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1)
                            .addComponent(sliderFrecuencia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(39, 39, 39)
                        .addComponent(jLabel2)))
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelLineal)
                    .addComponent(jPanelLineal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanelTermometro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void sliderFrecuenciaMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sliderFrecuenciaMouseReleased
        if(sliderFrecuencia.getValue()!=miEstacion.getFrecuencia()){
            miEstacion.enviarFrecuencia(sliderFrecuencia.getValue());
        }
    }//GEN-LAST:event_sliderFrecuenciaMouseReleased

    private void comboEstacionesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboEstacionesActionPerformed
        miEstacion.setEstacionSeleccionada(comboEstaciones.getSelectedItem().toString());
        if(!comboEstaciones.getSelectedItem().toString().equals(Constantes.ESTACION)){
            miEstacion.consultarTemperatura(comboEstaciones.getSelectedItem().toString());
        }        
    }//GEN-LAST:event_comboEstacionesActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        miEstacion.desconectar();
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox comboEstaciones;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabelLineal;
    private javax.swing.JLabel jLabelTermometro;
    private javax.swing.JPanel jPanelLineal;
    private javax.swing.JPanel jPanelTermometro;
    private javax.swing.JSlider sliderFrecuencia;
    // End of variables declaration//GEN-END:variables
    
    public void repintarGrafico(ArrayList temperaturas){
        XYSeries valores;
        JFreeChart grafico;
        JFreeChart termometro;
        
        valores = new XYSeries("Temperaturas Invernadero1");
        //Agrego los valores al gráfico
        for(int i = 0; i<temperaturas.size(); i++){
            Double temp = (Double)temperaturas.get(i);
            valores.add(i+1, temp.doubleValue());
        }
        //Establezco el valor del termometro
        plot.setDataset(new DefaultValueDataset((Double)temperaturas.get(temperaturas.size()-1)));
        //Creamos el grafico
        grafico = ChartFactory.createXYLineChart(comboEstaciones.getSelectedItem().toString(), 
                "Tiempo", 
                "Temperatura", 
                new XYSeriesCollection(valores), 
                PlotOrientation.VERTICAL, 
                true, 
                true, 
                false);
        NumberAxis rangeAxis = (NumberAxis)((XYPlot) grafico.getPlot()).getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        rangeAxis.setTickUnit(new NumberTickUnit(10));
        rangeAxis.setRange(0, 60);
        //Creamos el termometro
        termometro = new JFreeChart("Ultima Lectura",  // chart title
                JFreeChart.DEFAULT_TITLE_FONT,
                plot,                 // plot
                false);               // include legend
        //Generamos una imagen a partir del gráfico
        BufferedImage imagenGrafico = grafico.createBufferedImage(jPanelLineal.getWidth(), jPanelLineal.getHeight());
        BufferedImage imagenTermometro = termometro.createBufferedImage(180, 300);
        //Ponemos las imagenes en los paneles
        jLabelLineal.setSize(jPanelLineal.getSize());
        jLabelLineal.setIcon(new ImageIcon(imagenGrafico));
        jPanelLineal.updateUI();
        
        jLabelTermometro.setSize(jPanelTermometro.getSize());
        jLabelTermometro.setIcon(new ImageIcon(imagenTermometro));
        jPanelTermometro.updateUI();
    }
    
    public void addEstacion(String s){
        comboEstaciones.addItem(s);
    }
    
    public void mensajeRecibido(String s){
        //pendiente
    }
    
    public void delEstacion(String s){
        comboEstaciones.removeItem(s);
    }
    
    public void cambiarFrecuencia(int frecuencia){
        sliderFrecuencia.setValue(frecuencia);
    }


}
